#include "choosefrienddialog.h"

ChooseFriendDialog::ChooseFriendDialog(QWidget* parent, const QString& userId)
    :QDialog(parent), userId(userId)
{
    // 设置必要的属性
    this->setWindowTitle("选择好友");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setFixedSize(QSize(600, 500));

    QHBoxLayout* layout = new QHBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    this->setLayout(layout);

    // initialize left window
    initLeftWindow(layout);
    // initialize right window
    initRightWindow(layout);

    // load data
    initData();
}

void ChooseFriendDialog::initLeftWindow(QHBoxLayout *layout)
{
    // 滚动区域
    QScrollArea* scroll = new QScrollArea();
    scroll->setWidgetResizable(true);
    scroll->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height:0px; }");
    scroll->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width:1px solid rgb(1, 1, 1); }");
    layout->addWidget(scroll, 1);

    // 在滚动区域中添加 Widget
    totalWidget = new QWidget();
    totalWidget->setStyleSheet("QWidget { background-color:rgb(230, 230, 230); }");
    scroll->setWidget(totalWidget);

    // 垂直布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(5);
    vlayout->setContentsMargins(10, 10, 0, 10);
    totalWidget->setLayout(vlayout);

    // 添加元素
#if TEST_F
    QIcon icon(":/resource/image/default_avatar.png");
    for(int i = 0;i < 30;i ++) {
        this->addFriendItem(QString::number(1000 + i), false, icon, "张三" + QString::number(i));
    }
#endif
}

void ChooseFriendDialog::initRightWindow(QHBoxLayout *layout)
{
    // 右侧的布局管理器
    QGridLayout* gridLayout = new QGridLayout();
    gridLayout->setSpacing(0);
    gridLayout->setContentsMargins(5, 5, 5, 5);
    layout->addLayout(gridLayout, 2);

    // 标签
    QLabel* tag = new QLabel("选择联系人");
    tag->setStyleSheet("QLabel { font-size:20px; }");

    // 滚动区域
    QScrollArea* scroll = new QScrollArea();
    scroll->setWidgetResizable(true);
    scroll->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    scroll->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height:0px; }");
    scroll->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width:1px solid rgb(1, 1, 1); }");
    layout->addWidget(scroll);

    // 在滚动区域中添加 Widget
    selectWidget = new QWidget();
    selectWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    selectWidget->setStyleSheet("QWidget { background-color:rgb(230, 230, 230); }");
    scroll->setWidget(selectWidget);

    // 垂直布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setAlignment(Qt::AlignTop);
    vlayout->setSpacing(5);
    vlayout->setContentsMargins(0, 0, 0, 0);
    selectWidget->setLayout(vlayout);

    // 按钮
    QString style = "QPushButton { color:rgb(50, 145, 145); border-radius:5px; }";
    style += "QPushButton:hover { background-color:rgb(140, 140, 140); }";
    style += "QPushButton:pressed { background-color:rgb(50, 50, 50); }";

    QPushButton* okBtn = new QPushButton("完成");
    okBtn->setFixedHeight(30);
    okBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    okBtn->setStyleSheet(style);

    QPushButton* cancelBtn = new QPushButton("取消");
    cancelBtn->setFixedHeight(30);
    cancelBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    cancelBtn->setStyleSheet(style);

    // 将标签,滚动区域,按钮添加到布局管理器中
    gridLayout->addWidget(tag, 0, 0, 1, 9);
    gridLayout->addWidget(scroll, 1, 0, 1, 9);
    gridLayout->addWidget(okBtn, 2, 1, 1, 3);
    gridLayout->addWidget(cancelBtn, 2, 5, 1, 3);

#if 0
    // 添加测试数据
    QIcon icon(":/resource/image/default_avatar.png");
    for(int i = 0;i < 20;i ++) {
        this->addSelectedItem(QString::number(1000 + i), icon, "张三" + QString::number(i));
    }
#endif

    connect(okBtn, &QPushButton::clicked, this, [=](){
        QList<QString> userIdList = this->generateMemberList();
        if(userIdList.size() < 3) {
            Toast::makeToast("the number of people in group chat is less than 3");
            return;
        }
        model::DataCenter* dataCenter = model::DataCenter::getInstance();
        dataCenter->createGroupChatSessionAsync(userIdList);
        this->close();
    });

    connect(cancelBtn, &QPushButton::clicked, this, [=](){
        this->close();
    });
}

void ChooseFriendDialog::initData()
{
    // load data
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    QList<model::UserInfo>* list = dataCenter->getFriendList();
    if(list != nullptr) {
        for(auto &e : *list) {
            if(e.userId == userId) {
                this->addSelectedItem(e.userId, e.avatar, e.nickname);
                this->addFriendItem(e.userId, true, e.avatar, e.nickname);
            } else {
                this->addFriendItem(e.userId, false, e.avatar, e.nickname);
            }
        }
    }
}

void ChooseFriendDialog::addFriendItem(const QString& userId, bool selected, const QIcon &avatar, const QString &name)
{
    ChooseFriendItem* item = new ChooseFriendItem(userId, this, selected, avatar, name);
    totalWidget->layout()->addWidget(item);
}

void ChooseFriendDialog::addSelectedItem(const QString& userId, const QIcon &avatar, const QString &name)
{
    ChooseFriendItem* item = new ChooseFriendItem(userId, this, true, avatar, name);
    selectWidget->layout()->addWidget(item);
}

void ChooseFriendDialog::deleteFriendItem(const QString &userId)
{
    QVBoxLayout* vlayout = dynamic_cast<QVBoxLayout*>(this->selectWidget->layout());
    for(int i = vlayout->count() - 1;i >= 0;i --) {
        QLayoutItem* item = vlayout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if(chooseFriendItem->getUserId() != userId) {
            continue;
        }
        vlayout->removeWidget(chooseFriendItem);
        chooseFriendItem->deleteLater(); // 等到 Qt 执行完信号槽操作,在销毁
        // 点击 CheckBox 中的复选框取消后,调用该函数,一旦删除 chooseFriendItem
        // 会将 CheckBox 一并删除,后续的各种 Qt 内置行为就无法执行
        // 所以程序崩溃
        // delete chooseFriendItem;
    }

    // 遍历左侧的好友,将勾选上的复选框取消
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(this->totalWidget->layout());
    for(int i = 0;i < layout->count();i ++) {
        QLayoutItem* item = layout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* friendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if(friendItem->getUserId() != userId) {
            continue;
        }
        friendItem->getCheckBox()->setChecked(false);
    }
}

QList<QString> ChooseFriendDialog::generateMemberList()
{
    QList<QString> result;
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(selectWidget->layout());
    for(int i = 0;i < layout->count();i ++) {
        QLayoutItem* item = layout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* friendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        result.emplaceBack(friendItem->getUserId());
    }
    return result;
}

////////////////////////////////////////
/// 选择好友元素
////////////////////////////////////////

ChooseFriendItem::ChooseFriendItem(const QString& userId, ChooseFriendDialog* owner, bool selected, const QIcon& avatar, const QString& name)
    :userId(userId)
{
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(0, 0, 0, 0);
    this->setLayout(layout);

    // 复选框
    checkBox = new QCheckBox();
    checkBox->setFixedSize(QSize(30, 30));
    QString style = "QCheckBox::indicator { width:30px; height:30px; border-image:url(:/resource/image/unchecked.png); }";
    style += "QCheckBox::indicator:checked { border-image:url(:/resource/image/checked.png); }";
    style += "QCheckBox { background-color: transparent; }";
    checkBox->setChecked(selected);
    checkBox->setStyleSheet(style);

    // 头像
    avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(QSize(40, 40));
    avatarBtn->setIcon(avatar);
    avatarBtn->setIconSize(QSize(40, 40));
    avatarBtn->setStyleSheet("QPushButton { background-color: transparent; }");

    // 名字
    nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel { background-color: transparent; font-size:15px; }");

    layout->addWidget(checkBox);
    layout->addWidget(avatarBtn);
    layout->addWidget(nameLabel);

    // 点击复选框能添加到已选择列表/从选择列表删除
    connect(checkBox, &QCheckBox::toggled, this, [=](bool checked){
        if(checked) {
            // 添加到已选择区域
            owner->addSelectedItem(userId, avatar, name);
        } else {
            // 从已选择区域移除
            owner->deleteFriendItem(userId);
        }
    });
}

void ChooseFriendItem::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    if(selected) {
        // 将背景绘制成深色
        painter.fillRect(this->rect(), QColor(150, 150, 150));
    } else {
        // 将背景绘制成浅色
        painter.fillRect(this->rect(), QColor(230, 230, 230));
    }
}

void ChooseFriendItem::enterEvent(QEnterEvent *event)
{
    selected = true;
    this->update(); // 更新窗口
}

void ChooseFriendItem::leaveEvent(QEvent *event)
{
    selected = false;
    this->update(); // 更新窗口
}

const QString &ChooseFriendItem::getUserId()
{
    return userId;
}

QCheckBox *ChooseFriendItem::getCheckBox()
{
    return checkBox;
}
